package mgfacemq

import (
	"com.mgface.disobj/metanode/cluster"
	. "com.mgface.disobj/metanode/mq/mgfacemq/currentnodeinfo"
	"com.mgface.disobj/metanode/mq/mgfacemq/memory"
	"com.mgface.disobj/metanode/mq/mgfacemq/server"
	"context"
	"fmt"
	log "github.com/sirupsen/logrus"
	"os"
	"os/signal"
	"sync"
	"syscall"
	"time"
)

func Startengine(na, ca, gna, ms string) {

	memoryStore := &memory.Memorystore{
		StorePath:   ms,
		Mutex:       sync.RWMutex{},
		Datas:       make(map[string]interface{}),
		EnableClean: true,
	}
	serv := &server.Server{
		Store:     memoryStore,
		MutexServ: memoryStore.Mutex,
		Nodeinfo:  &CurrentNodeInfo{NodeFlag: "slave"},
	}

	//启动节点识别
	go cluster.GossipDect(na, ca, gna, serv)

	pid := os.Getpid()
	log.Info(fmt.Sprintf("当前PID: 【%d】 ", pid), "启动metadataNode...")
	//刷新内存数据和保持内存数据到文件中
	go serv.FlushData(serv.Nodeinfo)

	//启动显示当前内存数据
	go func() {
		for {
			memoryData := serv.Show()
			fmt.Println("内存数据:", memoryData)
			time.Sleep(3 * time.Second)
		}
	}()

	rootContext := context.Background()
	//创建一个可以取消的ctx
	ctx, cancelFunc := context.WithCancel(rootContext)
	//启动tcp监听服务
	go serv.Listen(na, ctx)

	ch := make(chan os.Signal)
	signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
	log.Debug(<-ch)
	//优雅的停止服务.
	cancelFunc()
	time.Sleep(3 * time.Second)
	log.Debug("停止服务.")

}
